package dao

import (
	"errors"
	"log"
	"wow-web/models"
)

type accountDao struct {
}

func newAccountDao() *accountDao {
	return new(accountDao)
}

func (dao *accountDao) FindByUserName(username string) *models.Account {
	db, e := getConn()
	if e != nil {
		log.Println(e)
		return nil
	}
	defer db.Close()
	account := &models.Account{}
	sql := `select username,sha_pass_hash,reg_mail,email from account where username=?`
	e = db.Get(account, sql, username)
	if e != nil {
		return nil
	}
	return account
}

func (dao *accountDao) FindByRegMail(mail string) *models.Account {
	db, e := getConn()
	if e != nil {
		log.Println(e)
		return nil
	}
	defer db.Close()
	account := &models.Account{}
	sql := `select username,sha_pass_hash,reg_mail,email from account where reg_mail=?`
	e = db.Get(account, sql, mail)
	if e != nil {
		return nil
	}
	return account
}

func (dao *accountDao) CreateAccount(account *models.Account) error {
	db, e := getConn()
	if e != nil {
		log.Println(e)
		return e
	}

	sql := `INSERT INTO account(username, sha_pass_hash, reg_mail, email, joindate)
VALUES(?, ?, ?, ?, NOW())`
	_, e1 := db.Exec(sql, account.Username, account.ShaPassHash, account.RegMail, account.Email)
	if e1 != nil {
		log.Println(e1)
		return errors.New("数据库异常")
	}
	return nil
}
